package main.chapter6.async

import kotlin.coroutines.AbstractCoroutineContextElement
import kotlin.coroutines.Continuation
import kotlin.coroutines.ContinuationInterceptor

class AsyncContext : AbstractCoroutineContextElement(ContinuationInterceptor), ContinuationInterceptor {
    override fun <T> interceptContinuation(continuation: Continuation<T>): Continuation<T> {
        return UIContinuationWrapper(continuation.context
            .fold(continuation) { continuation, element ->
                //当修改的对象不是自己并且具备修改能力
                if (element != this && element is ContinuationInterceptor) {
                    element.interceptContinuation(continuation)
                } else continuation
            })
    }
}